package com.tongtailian.www.stir.fragment;


import android.Manifest;
import android.androidlib.utils.ACache;
import android.androidlib.utils.JSONUtils;
import android.app.Activity;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothGatt;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.clj.fastble.BleManager;
import com.clj.fastble.data.BleDevice;
import com.clj.fastble.exception.BleException;
import com.clj.fastble.scan.BleScanRuleConfig;
import com.tongtailian.www.stir.MyApplication;
import com.tongtailian.www.stir.R;
import com.tongtailian.www.stir.adapter.BluetoothDeviceAdapter;
import com.tongtailian.www.stir.bean.ConfigDataFram;
import com.tongtailian.www.stir.bean.DeviceUseFram;
import com.tongtailian.www.stir.bleinterface.MyBleGattCallback;
import com.tongtailian.www.stir.bleinterface.MyBleScanCallBack;
import com.tongtailian.www.stir.operation.OperationActivity;
import com.tongtailian.www.stir.utils.BleManageUtil;
import com.tongtailian.www.stir.utils.LogUtil;
import com.tongtailian.www.stir.utils.ParcelableUtil;
import com.tongtailian.www.stir.utils.ToastUtils;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author liuml
 * @explain
 * @time 2020/9/16 22:18
 */
public class MyDialogFragment extends BottomDialog implements View.OnClickListener {

    private static final int REQUEST_CODE_OPEN_GPS = 1;
    private static final int REQUEST_CODE_PERMISSION_LOCATION = 2;
    public Mydialoginterface dialogInterface;
    public Activity activity;
    private View inflate;
    private int height;
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    private String string;
    private Button btnScan;
    private ImageView imgLoading;
    private RecyclerView recycleview;
    private Animation operatingAnim;
    private BluetoothDeviceAdapter mDeviceAdapter;
    private Button btnScanBlue;
    private RecyclerView recycleviewOld;
    public LinearLayout llLeft;


    private Button read;
    private Button write;
    private Button notifly;
    private TextView tvTxtData;
    private Button start;
    private Button stop;

    private  ACache aCache;
    BleManager bleManager;
    BleDevice mBleDevice;

//    private ConfigDataFram notiflyConfigData;
    private MyBleGattCallback myBleGattCallback;

    public interface Mydialoginterface extends DialogInterface {
    }


    public static final MyDialogFragment newInstance(int param1) {

        MyDialogFragment fragment = new MyDialogFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_PARAM1, param1);
        fragment.setArguments(args);
        return fragment;
    }


    public MyBleGattCallback getMyBleGattCallback() {
        return myBleGattCallback;
    }

    public void setMyBleGattCallback(MyBleGattCallback myBleGattCallback) {
        this.myBleGattCallback = myBleGattCallback;
    }

    public void setInterface(Mydialoginterface dialogInterface) {
        LogUtil.d("dialogInterface = " + dialogInterface);
        this.dialogInterface = dialogInterface;
    }

    @Override
    public void onStart() {
        super.onStart();
        //设置 dialog 的宽高
        if (height > 0) {
            getDialog().getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, height);
        } else {
            getDialog().getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        }
        //设置 dialog 的背景为 null
        getDialog().getWindow().setBackgroundDrawable(null);
    }

    @Override
    public void onDismiss(@NonNull DialogInterface dialog) {
        super.onDismiss(dialog);
        LogUtil.d("onDismiss 被调用  dialogInterface = " + dialogInterface);
        if (dialogInterface != null) {
            LogUtil.d("dialogInterface != null  onDismiss 被调用");
            dialogInterface.dismiss();
        }
    }

    public void setActivity(Activity activity) {
        this.activity = activity;
    }

    @Override
    protected View createView(LayoutInflater inflater, ViewGroup container) {
        if (getArguments() != null) {
            height = getArguments().getInt(ARG_PARAM1);
//            LogUtil.d("传递过来的 = " + string);
        }
        //这里设置dialogfragment 的布局
        inflate = inflater.inflate(R.layout.dialog_fragment, container);

        initView();
//        if (height > 0) {
//            View view = inflate.findViewById(R.id.ll_contener);
//            view.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, height));
//        }

        initData();
        return inflate;
    }

    private void initView() {
        btnScan = inflate.findViewById(R.id.btn_scan);
        imgLoading = inflate.findViewById(R.id.img_loading);
        recycleview = inflate.findViewById(R.id.recycleview);
        btnScanBlue = inflate.findViewById(R.id.btn_scan_blue);//扫描设备
        recycleviewOld = inflate.findViewById(R.id.recycleview_old);//以前连接的设备
        llLeft = inflate.findViewById(R.id.ll_left);
        tvTxtData = inflate.findViewById(R.id.tv_txtData);

        start = inflate.findViewById(R.id.start);

        stop = inflate.findViewById(R.id.stop);

        tvTxtData.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //获取剪贴板管理器：
                ClipboardManager cm = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
                // 创建普通字符型
                ClipData mClipData = ClipData.newPlainText("Label", tvTxtData.getText().toString());
                // 将ClipData内容放到系统剪贴板里。
                cm.setPrimaryClip(mClipData);
                ToastUtils.showShort("拷贝成功");
            }
        });
        read = inflate.findViewById(R.id.read);

        write = inflate.findViewById(R.id.write);
        notifly = inflate.findViewById(R.id.notifly);

        operatingAnim = AnimationUtils.loadAnimation(getActivity(), R.anim.rotate);
        operatingAnim.setInterpolator(new LinearInterpolator());

        btnScan.setOnClickListener(this);

        mDeviceAdapter = new BluetoothDeviceAdapter(R.layout.adapter_device, BleManageUtil.getInstance().getDevices());
        recycleview.setLayoutManager(new LinearLayoutManager(getActivity()));
        recycleview.setAdapter(mDeviceAdapter);
        myBleGattCallback = new MyBleGattCallback() {
            @Override
            public void onStartConnect() {
            }

            @Override
            public void onConnectFail(BleDevice bleDevice, BleException exception) {
                imgLoading.clearAnimation();
                imgLoading.setVisibility(View.INVISIBLE);
                try {
                    ToastUtils.showCenter("蓝牙异常");
                    if (btnScan != null) {
                        btnScan.setText(getString(R.string.start_scan));
                    }
                } catch (Exception e) {

                }
            }

            @Override
            public void onConnectSuccess(BleDevice bleDevice, BluetoothGatt gatt, int status) {
                mBleDevice = bleDevice;
                mDeviceAdapter.setNewData(BleManageUtil.getInstance().getDevices());

                aCache.put("Bluetooth", ParcelableUtil.marshall(bleDevice));
                ToastUtils.showCenter("连接成功");
                dismiss();
            }

            @Override
            public void onDisConnected(boolean isActiveDisConnected, BleDevice device, BluetoothGatt gatt, int status) {
                //断开连接 需要弹窗重新连接

            }
        };

        mDeviceAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                BleDevice bleDevice = BleManageUtil.getInstance().getDevices().get(position);
                switch (view.getId()) {
                    case R.id.btn_connect://开始连接
                        if (!BleManager.getInstance().isConnected(bleDevice)) {
                            BleManager.getInstance().disconnectAllDevice();
                            BleManager.getInstance().cancelScan();
                            BleManageUtil.getInstance().connect(bleDevice);
                        } else {
                            ToastUtils.showCenter("已经连接");
                        }
                        break;
                    case R.id.btn_disconnect://断开连接
                        if (BleManager.getInstance().isConnected(bleDevice)) {
                            BleManager.getInstance().disconnect(bleDevice);
                        }
                        break;
                    case R.id.btn_detail:
                        //开始操作
                        if (BleManager.getInstance().isConnected(bleDevice)) {
                            Intent intent = new Intent(getActivity(), OperationActivity.class);
                            intent.putExtra(OperationActivity.KEY_DATA, bleDevice);
                            startActivity(intent);
                        }
                        break;
                }
            }
        });


        /**
         * 通知
         */
        notifly.setOnClickListener(this);
        start.setOnClickListener(this);
        stop.setOnClickListener(this);


        //00 起始位 , 06 字节数, 00 索引? . 61 命令 . 01 参数 1 字节, 进入工作流程 //Byte[0]: 工作参数组编号. 00 数据 . 66 校验 长度开始到数据最后一个字节，逐字异或
        //进入工作流程 00 06 00 61 01 00 66
        String input = "00060061010066";
//        String input = "00060061010066";
//        reverseData("000600610100");

        int length = getLength(input);
        LogUtil.d("字节长度 = " + length);
        LogUtil.d("字节长度2 = " + input.getBytes().length);

        /**
         * 写入配置
         */
        write.setOnClickListener(this);
        /**
         * 读取配置
         */
        read.setOnClickListener(this);

        if (llLeft != null) {
            llLeft.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dismiss();
                }
            });
        }

    }

    // 编码方式
    private static final String ENCODE_UTF = "UTF-8";

    public static int getLength(String str) {
        if (str == null || str.length() == 0) {
            return 0;
        }
        try {
            return str.getBytes(ENCODE_UTF).length;
        } catch (UnsupportedEncodingException e) {
            LogUtil.e("计算字符串的字节长度失败，");
        }
        return 0;
    }

    /**
     * 高低位转换的工具 地址 反转
     *
     * @param data
     * @return
     */
    public static String reverseData(String data) {
        int length = data.length() / 2;
        String result = "";
        for (int i = 0; i < length; i++) {
            result += data.substring(data.length() - 2, data.length());
            data = data.substring(0, data.length() - 2);
        }
        LogUtil.d("高低位转换的工具 " + data);
        return result;
    }


    private void initData() {
        aCache = ACache.get(MyApplication.getAppInstance());
        bleManager = BleManager.getInstance();
        BleScanRuleConfig scanRuleConfig = new BleScanRuleConfig.Builder()
//                .setServiceUuids(serviceUuids)      // 只扫描指定的服务的设备，可选
//                .setDeviceName(true, names)         // 只扫描指定广播名的设备，可选
//                .setDeviceMac(mac)                  // 只扫描指定mac的设备，可选
//                .setAutoConnect(isAutoConnect)      // 连接时的autoConnect参数，可选，默认false
                .setScanTimeOut(10000)              // 扫描超时时间，可选，默认10秒；小于等于0表示不限制扫描时间
                .build();

        BleManager.getInstance().initScanRule(scanRuleConfig);


    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {

            case R.id.write:
                //80 第一个用户组 81 第二个组
                ConfigDataFram dataFram = new ConfigDataFram("80", "");
                dataFram.setcGroupName("工作组0");
                //4 均质工作时间  0-60 秒
                dataFram.setiTimeWork(231);
                //均质工作下降时电机转速 转刀转速 上限18000
                dataFram.setiMotorSpeed(8000);

                //渐进研磨
                dataFram.setcCountWork(1);

                //                //4 超声波清洗时间
                dataFram.setiTimeSuper(302);
                //2 超声波位甩干次数 超声波清洗次数
                dataFram.setcCountSuper(1);

                //                //4 清水清洗时间
                dataFram.setiTimeWater(312);
                //清水清洗次数
                dataFram.setcCountWater(1);


                //是否添加洗涤剂
                dataFram.setcCountClear(1);

                //是否有烘干
                dataFram.setcClrSelect(5);


//                //4 iWorkFlwTime //未选中 则为0
//                dataFram.setiWorkFlwTime(60);
//                //2 清水位甩干次数
//                dataFram.setcCountWater(1);
//                //2 加入洗涤剂到超声波槽
//                dataFram.setiInClear(1);
                LogUtil.d("生成数据= " + dataFram.toString());
//                final String data1 = dataFram.createData(BleManageUtil.getInstance().getConfigDataFrame());
//                LogUtil.d("生成data = " + data1);
//                BleManageUtil.getInstance().writeData(data1);
                break;
            case R.id.read:

                //读取设备版本
//                DevicesInfoBean devicesInfoBean = new DevicesInfoBean("f1","00");
//                //版本号设备  f100 返回的是 f100 + 字符串
//                String sendData = devicesInfoBean.getSendData();
//                LogUtil.d("设备信息发送 获取 = "+sendData);
//                writeData(sendData);
//                BleManageUtil.getInstance().readDevicesState();

                break;
            case R.id.notifly://读取通知
//                ConfigDataFram configDataFram2 = new ConfigDataFram("00", "");
                ConfigDataFram configDataFram2 = new ConfigDataFram("00", "");
//                ConfigDataFram configDataFram2 = new ConfigDataFram("00", "");
                String data2 = configDataFram2.getSendData();
                LogUtil.d("参数读取notifly : " + data2);
                LogUtil.d("参数读取configDataFram2 : " + JSONUtils.toJSON(configDataFram2));
                BleManageUtil.getInstance().writeData(data2);//发送数据
                LogUtil.d("获取配置");
//                writeData("00060060000066");
//                writeData("000500700277");
//                writeData("000500F100F4");//设备版本
                break;
            case R.id.start:
//                开启流程
                DeviceUseFram deviceUseFram = new DeviceUseFram("01", "");
                deviceUseFram.setGroup(0);
                deviceUseFram.setLoop(1);
                deviceUseFram.setWorkLocation1(1);
                deviceUseFram.setWorkLocation2(0);
                deviceUseFram.setWorkLocation3(0);
                deviceUseFram.setWorkLocation4(0);
                String data = deviceUseFram.createData();
//                BleManageUtil.getInstance().writeData(data);
                break;
            case R.id.stop:
//                停止流程
                DeviceUseFram deviceUseFramStop = new DeviceUseFram("00", "00");
                String sendData1 = deviceUseFramStop.getSendData();
                BleManageUtil.getInstance().writeData(sendData1);
                break;
            case R.id.btn_scan:
                if (btnScan.getText().equals(getString(R.string.start_scan))) {
//                    BleManager.getInstance().disconnect(bleDevice);
                    checkPermissions();
                } else if (btnScan.getText().equals(getString(R.string.stop_scan))) {
                    BleManager.getInstance().cancelScan();
                }
                break;

        }
    }


    private void checkPermissions() {
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (!bluetoothAdapter.isEnabled()) {
            ToastUtils.showCenter(getString(R.string.please_open_blue));
            return;
        }

        String[] permissions = { Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.ACCESS_FINE_LOCATION};
        List<String> permissionDeniedList = new ArrayList<>();
        for (String permission : permissions) {
            int permissionCheck = ContextCompat.checkSelfPermission(getActivity(), permission);
            if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
                onPermissionGranted(permission);
            } else {
                permissionDeniedList.add(permission);
            }
        }
        if (!permissionDeniedList.isEmpty()) {
            String[] deniedPermissions = permissionDeniedList.toArray(new String[permissionDeniedList.size()]);
            ActivityCompat.requestPermissions(getActivity(), deniedPermissions, REQUEST_CODE_PERMISSION_LOCATION);
        }
    }

    private void onPermissionGranted(String permission) {
        /**
         * 垃圾平板没有GPS开启
         */
        BleManageUtil.getInstance().startScan(new MyBleScanCallBack() {
            @Override
            public void onLeScanList(List<BleDevice> devices) {
                mDeviceAdapter.setNewData(devices);
            }

            @Override
            public void onScanStarted(boolean success) {
                mDeviceAdapter.notifyDataSetChanged();
                imgLoading.startAnimation(operatingAnim);
                imgLoading.setVisibility(View.VISIBLE);
                btnScan.setText(getString(R.string.stop_scan));
            }

            @Override
            public void onScanning(BleDevice bleDevice) {

            }

            @Override
            public void onScanFinished(List<BleDevice> scanResultList) {
                mDeviceAdapter.setNewData(scanResultList);

                imgLoading.clearAnimation();
                imgLoading.setVisibility(View.INVISIBLE);
                try {
                    btnScan.setText(getString(R.string.start_scan));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        /*switch (permission) {
            case Manifest.permission.ACCESS_FINE_LOCATION:
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !checkGPSIsOpen()) {
                    new AlertDialog.Builder(getActivity())
                            .setTitle(R.string.notifyTitle)
                            .setMessage(R.string.gpsNotifyMsg)
                            .setNegativeButton(R.string.cancel,
                                    new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            dismiss();
                                        }
                                    })
                            .setPositiveButton(R.string.setting,
                                    new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                                            startActivityForResult(intent, REQUEST_CODE_OPEN_GPS);
                                        }
                                    })

                            .setCancelable(false)
                            .show();
                } else {
                    BleManageUtil.getInstance().startScan(new MyBleScanCallBack() {
                        @Override
                        public void onLeScanList(List<BleDevice> devices) {
                            mDeviceAdapter.setNewData(devices);
                        }

                        @Override
                        public void onScanStarted(boolean success) {
                            mDeviceAdapter.notifyDataSetChanged();
                            imgLoading.startAnimation(operatingAnim);
                            imgLoading.setVisibility(View.VISIBLE);
                            btnScan.setText(getString(R.string.stop_scan));
                        }

                        @Override
                        public void onScanning(BleDevice bleDevice) {

                        }

                        @Override
                        public void onScanFinished(List<BleDevice> scanResultList) {
                            mDeviceAdapter.setNewData(scanResultList);

                            imgLoading.clearAnimation();
                            imgLoading.setVisibility(View.INVISIBLE);
                            try {
                                btnScan.setText(getString(R.string.start_scan));
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    });
                }
                break;
        }*/
    }


    private boolean checkGPSIsOpen() {
        LocationManager locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
        if (locationManager == null) {
            return false;
        }
        return locationManager.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER);
    }

//
}

